package com.charity.controller;

import com.charity.service.IPasswordResetService;
import com.charity.security.JwtUtils;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/auth")
public class AuthController {

    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(AuthController.class);

    @Resource
    private DefaultKaptcha defaultKaptcha;

    @Resource
    private IPasswordResetService passwordResetService;

    @Resource
    private StringRedisTemplate redisTemplate;

    @Resource
    private JwtUtils jwtUtils;

    private static final String CAPTCHA_PREFIX = "captcha:";

    @GetMapping("/captcha")
    public ResponseEntity<Map<String, Object>> getCaptcha(HttpServletRequest request) throws Exception {
        log.info("Received captcha request from session: {}", request.getSession().getId());
        // 生成验证码文本
        String text = defaultKaptcha.createText();
        // 获取会话ID
        String sessionId = request.getSession().getId();
        // 将验证码存储到Redis，设置60秒过期时间
        redisTemplate.opsForValue().set(CAPTCHA_PREFIX + sessionId, text, 60, TimeUnit.SECONDS);
        // 生成验证码图片
        BufferedImage image = defaultKaptcha.createImage(text);
        // 将图片转换为Base64
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", baos);
        String base64Image = java.util.Base64.getEncoder().encodeToString(baos.toByteArray());
        
        Map<String, Object> response = new HashMap<>();
        response.put("sessionId", sessionId);
        response.put("image", "data:image/jpeg;base64," + base64Image);
        return ResponseEntity.ok(response);
    }

    @PostMapping("/reset-password/send-code")
    public ResponseEntity<Map<String, Object>> sendResetCode(@RequestBody Map<String, String> params) {
        Map<String, Object> response = new HashMap<>();
        String email = params.get("email");
        
        if (passwordResetService.sendResetCode(email)) {
            response.put("code", 200);
            response.put("message", "验证码已发送到邮箱");
        } else {
            response.put("code", 400);
            response.put("message", "邮箱不存在或发送失败");
        }
        return ResponseEntity.ok(response);
    }

    @PostMapping("/reset-password/verify-code")
    public ResponseEntity<Map<String, Object>> verifyResetCode(@RequestBody Map<String, String> params) {
        Map<String, Object> response = new HashMap<>();
        String email = params.get("email");
        String code = params.get("code");

        if (passwordResetService.verifyResetCode(email, code)) {
            response.put("code", 200);
            response.put("message", "验证码验证成功");
        } else {
            response.put("code", 400);
            response.put("message", "验证码错误或已过期");
        }
        return ResponseEntity.ok(response);
    }

    @PostMapping("/reset-password")
    public ResponseEntity<Map<String, Object>> resetPassword(@RequestBody Map<String, String> params) {
        Map<String, Object> response = new HashMap<>();
        String email = params.get("email");
        String newPassword = params.get("newPassword");
        String code = params.get("code");

        if (passwordResetService.resetPassword(email, newPassword, code)) {
            response.put("code", 200);
            response.put("message", "密码重置成功");
        } else {
            response.put("code", 400);
            response.put("message", "密码重置失败");
        }
        return ResponseEntity.ok(response);
    }
}